<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" size="small">
    <el-form-item label="分类名称" prop="classifyName">
      <el-input v-model.trim="ruleForm.classifyName" placeholder="请输入分类名称"></el-input>
    </el-form-item>

    <el-form-item label="分类icon" prop="classifyIcon">
      <el-input v-model="ruleForm.classifyIcon" class="hide" />
      <el-upload
        :action="$V.uploadURL"
        :headers="{token: $getToken()}"
        :on-success="(...args) => handleUploadSuccess('classifyIcon', ...args)"
        :on-remove="(...args) => handleUploadRemove('classifyIcon', ...args)"
        :on-error="handleUploadError"
        :file-list="iconFileList"
        :class="iconSingle ? 'single' : ''"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>

    <el-form-item label="分类图片" prop="classifyImage">
      <el-input v-model="ruleForm.classifyImage" class="hide" />
      <el-upload
        :action="$V.uploadURL"
        :headers="{token: $getToken()}"
        :on-success="(...args) => handleUploadSuccess('classifyImage', ...args)"
        :on-remove="(...args) => handleUploadRemove('classifyImage', ...args)"
        :on-error="handleUploadError"
        :file-list="classifyFileList"
        :class="classifySingle ? 'single' : ''"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>

    <el-form-item label="首页展示" prop="classifyShowHome">
      <el-switch
        v-model="ruleForm.classifyShowHome"
        active-color="#13ce66"
        inactive-color="#ff4949"
      ></el-switch>
    </el-form-item>

    <el-form-item label="排序" prop="classifySort">
      <el-input v-model.number="ruleForm.classifySort" placeholder="请输入排序"></el-input>
    </el-form-item>

    <el-form-item label="分类简介" prop="classifySummary">
      <el-input
        v-model.trim="ruleForm.classifySummary"
        placeholder="请输入分类简介"
        type="textarea"
        :rows="4"
      ></el-input>
    </el-form-item>
  </el-form>
</template>

<script>
/* Mixins
------------------------------- */
import { Form } from '@/mixins'

/* Api
------------------------------- */
import { checkFreshCategoryName } from '@/api'

/* Model
------------------------------- */
import { freshCategoryModel, primaryKey } from '../model'

export default {
  mixins: [Form('ruleForm', freshCategoryModel)],
  data () {
    const asyncCheckFreshCategoryName = (rule, value, callback) => {
      return this.checkFreshCategoryName(
        {
          name: value,
          id: this.ruleForm[primaryKey]
        },
        {
          onOk ({ data }) {
            !data ? callback(new Error('当前分类名称已存在')) : callback()
          },
          onError ({ message }) {
            callback(new Error(message))
          }
        }
      )
    }

    return {
      ruleForm: Object.assign({}, freshCategoryModel),
      rules: {
        classifyName: [
          {
            required: true,
            message: this.$t('required', { field: '分类名称' })
          },
          { validator: asyncCheckFreshCategoryName, trigger: 'blur' }
        ],
        classifySummary: [
          {
            required: true,
            message: this.$t('required', { field: '分类简介' })
          }
        ],
        classifySort: [
          {
            required: true,
            message: this.$t('required', { field: '分类排序' })
          }
        ],
        classifyImage: [
          {
            required: true,
            message: this.$t('required', { field: '分类图片' })
          }
        ],
        classifyIcon: [
          {
            required: true,
            message: this.$t('required', { field: '分类icon' })
          }
        ]
      },

      iconFileList: [],
      classifyFileList: [],
      iconSingle: false,
      classifySingle: false
    }
  },
  methods: {
    // --------------------------------------  request --------------------------------------
    checkFreshCategoryName ({ name, id }, { onOk, onError }) {
      return this.Catch(checkFreshCategoryName, {
        onOk,
        onError
      })(null, name, id)
    },

    handleUploadSuccess (field, res, file, fileList) {
      if (res.result !== httpStatus.OK) {
        this.$message.error(res.message)
        return
      }
      this.ruleForm[field] = res.data

      if (field === 'classifyIcon') {
        this.iconSingle = fileList.length === 1
      } else {
        this.classifySingle = fileList.length === 1
      }
    },

    handleUploadError (_, file, fileList) {
      this.$message.error(this.$t('fileUploadError'))
    },

    handleUploadRemove (field, file, fileList) {
      if (field === 'classifyIcon') {
        this.ruleForm['classifyIcon'] = ''
        this.updateIconFileList()
        this.iconSingle = false
      } else {
        this.ruleForm['classifyImage'] = ''
        this.updateClassifyFileList()
        this.classifySingle = false
      }
    },

    updateIconFileList () {
      this.iconFileList = this.ruleForm.classifyIcon
        .split(',')
        .filter(Boolean)
        .map((it) => {
          return {
            name: it,
            url: this.$V.staticBaseURL + it
          }
        })

      this.iconSingle = this.iconFileList.length > 0
    },
    updateClassifyFileList () {
      this.classifyFileList = this.ruleForm.classifyImage
        .split(',')
        .filter(Boolean)
        .map((it) => {
          return {
            name: it,
            url: this.$V.staticBaseURL + it
          }
        })
      this.classifySingle = this.classifyFileList.length > 0
    }

    // -------------------------------------- !request --------------------------------------
  },
  computed: {},

  mounted () {
    this.updateIconFileList()
    this.updateClassifyFileList()
  }
}
</script>
